import 'dart:convert';

import 'package:dio/dio.dart';

class DioService {
  final Dio dio = Dio();

  late var _baseUrl = "";

  set baseUrl(value) {
    if (_baseUrl == value) {
      return;
    }
    _baseUrl = value;
    dio.options.baseUrl = _baseUrl;
  }

  get baseUrl => _baseUrl;

  String serviceKey() {
    return "";
  }

  // 初始化dio
  void initDio() {}

  // 添加公共请求头、公共参数
  Map<String, dynamic>? serviceHeader() {
    return null;
  }

  Map<String, dynamic>? serviceQuery() {
    return null;
  }

  Map<String, dynamic>? serviceBody() {
    return null;
  }

  // 添加公共结果处理、错误处理
  dynamic responseFactory(dynamic dataMap) {
    // 可对请求结果进行加工处理
    return dataMap;
  }

  String? errorFactory(DioError error) {
    // 请求错误处理
    String? errorMessage = error.message;
    switch (error.type) {
      case DioErrorType.connectionTimeout:
        errorMessage = "Connection timeout！";
        break;
      case DioErrorType.receiveTimeout:
        errorMessage = "Receive timeout!";
        break;
      case DioErrorType.sendTimeout:
        errorMessage = "Send timeout";
        break;
      case DioErrorType.badResponse:
        try {
          int? errCode = error.response?.statusCode;
          switch (errCode) {
            case 500:
              errorMessage = "服务器错误";
              break;
            case 400:
              errorMessage = json.encode(error.response!.data);
              print("验证失败：${error.error}");
              print("验证失败：${error.requestOptions.data}");
              print("验证失败：${error.type}");
              print("验证失败：${error.stackTrace}");
              print("验证失败：${error.response}");
              print("验证失败：${error.response!.statusCode}");
              break;
          }
        } on Exception catch (_) {
          errorMessage = error.message;
        }
        break;
      default:
        errorMessage = error.message;
        break;
    }
    // 具体的错误处理
    return errorMessage;
  }
}